package com.jky.trial.aop;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jky.trial.annotation.NoRepeatSubmit;
import com.jky.trial.common.BaseResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

@Aspect
@Component
public class NoRepeatSubmitAop {
    private Log logger = LogFactory.getLog(getClass());

    private Cache<String,Long> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(500).build();

//    private Map<String,Long> cache = new HashMap();


    @Around("execution(* com.jky.trial.controller.*Controller.*(..)) && @annotation(nrs)")
    public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String sessionId = request.getHeader("tk");
            Object o = null;
            if (!(request.getMethod().toLowerCase().equals("post") || request.getMethod().toLowerCase().equals("put"))) {
                return pjp.proceed();
            }
            String key = request.getMethod() + sessionId + "-" + request.getServletPath();
            Long lastTime = cache.getIfPresent(key), now = System.currentTimeMillis();
//            System.out.println(key);
//            System.out.println(lastTime);
//            System.out.println(now);
            if (lastTime == null) {// 如果缓存中有这个url视为重复提交
                cache.put(key, now); //
                o = pjp.proceed();
                return o;
            } else if (lastTime + 500 > now) { //半秒内提交2次
                cache.put(key, now);
                logger.error("重复提交");
                return new BaseResult(false, "请勿多次重复提交", 0);
            } else {
                o = pjp.proceed();
                return o;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("验证重复提交时出现未知异常!");
            return new BaseResult(false, "请勿多次重复提交", 0);
        }

    }
}
